<template>
	<view class="aclist">
		<view class="items" v-for="(item,index) in list" :key="index">
			<image :src="item.url" class="items_i"></image>
			<view class="items_z"><text class="t-icon t-icon-remenhuodong"></text>{{ item.title }}</view>
			<view class="items_ar">
				<view class="ar_a"><text class="t-icon t-icon-dizhi"></text>{{ item.location }}</view>
				<view class="ar_a"><uni-icons type="staff-filled" size="20"></uni-icons>{{ item.peopleCount }}</view>
			</view>
			<view class="items_ti">
				<text style="padding-right: 10rpx;">{{item.beginTime}}</text>至<text
					style="padding-left: 10rpx;">{{item.endTime}}</text>
			</view>
			<view class="items_c">{{ item.content }}</view>
			<view class="items_cz">
				<view class="items_czf">
					<text class="cz_btn bianj" @click="editActivity(item)">编辑</text>
					<text class="cz_btn shanc" @click="delActivity(item)">删除</text>
				</view>
				<button class="haibao" @click="GeneratePoster(item)">生成海报</button>
			</view>
		</view>
		<view style="height: 100rpx;"></view>
		<view class="toolbars">
			<view class="button-grounp">
				<view class="button payment-button" @tap="onSubAddActivisy()">
					新建活动
				</view>
			</view>
		</view>

		<!-- 新建主题 -->
		<view @touchmove.stop.prevent="moveHandle">
			<uni-popup ref="popup" :mask-click="false" border-radius="20px 20px 0px 0px" background-color="#fff" type="bottom"
				class="filter-popup" :height="height" @close="close">

				<view class="top-title flex-row-sb" v-if="showTop">
					<view class="popup-title">{{ title }}</view>
					<uni-icons type="closeempty" size="20" class="saasIcon" @click="close"></uni-icons>
				</view>
				<scroll-view class="select-scroll" scroll-y :style="{ height: `calc( ${height} - 120rpx - 152rpx  )` }">
					<view class="input-main">
						<black v-for="(item, index) in inputData" :key="index">
							<template v-if="item.type == 'text'">
								<view class="input-item">
									<label class="input-label">{{ item.title }}<text v-if="item.required"
											style="color: #FF0000;">*</text></label>
									<input :placeholder="item.placeholder" v-model="item.inpValue"
										class="input-field" />
								</view>
							</template>
							<template v-else="item.type == 'textarea'">
								<view class="input-items">
									<label class="input-label">{{ item.title }}<text v-if="item.required"
											style="color: #FF0000;">*</text></label>
									<textarea :placeholder="item.placeholder" v-model="item.inpValue"
										class="uni-textarea input-textarea" />
								</view>
							</template>
						</black>

						<view class="input-item">
							<label class="input-label">活动开始时间<text style="color: #FF0000;">*</text></label>
							<leeDatetime @change="startDateChange" placeholder="活动开始时间" class="input-field"
								:value="beginTime"></leeDatetime>
						</view>
						<view class="input-item">
							<label class="input-label">活动结束时间<text style="color: #FF0000;">*</text></label>
							<leeDatetime @change="endDateChange" placeholder="活动结束时间" class="input-field"
								:value="endTime"></leeDatetime>
						</view>
						<uni-section title="选择背景图" type="line">
							<uni-file-picker v-model="fileList" limit="1" title="选择背景图" @select="selectBackground"
								@delete="deleteBackground"></uni-file-picker>
						</uni-section>
					</view>
				</scroll-view>
				<view style="height: 160rpx;"></view>
				<view class="filter-button flex-row-c">
					<view class="btn flex-row">
						<view class="btn-1 flex-row-c-c" @click="reset">重置</view>
						<view class="btn-2 flex-row-c-c" @click="finsh">提交</view>
					</view>
				</view>

			</uni-popup>
		</view>

	</view>
</template>

<script>
	import {
		postSaveOrUpdateActivity,
		getActivityList,
		// postFileDelete,
		postFileInsert
	} from "@/proxy/activity/activity.api.js";
	import leeDatetime from "@/components/lee-datetime/lee-datetime.vue"
	export default {
		components: {
			leeDatetime
		},
		data() {
			return {
				showTop: true,
				height: "1200rpx",
				title: "",
				beginTime: "", // 活动开始时间
				endTime: "", //活动结束时间
				fileList: [], // 上传后的图片路径数组
				id:"", // 修改id
				inputData: [
					{
						title: "活动标题",
						placeholder: "请输入活动标题",
						inpValue: "",
						key: "title", //键名 接收对象名字
						required: true,
						type: "text"
					},
					{
						title: "参与地点",
						placeholder: "请输入参与地点",
						inpValue: "",
						key: "location", //键名 接收对象名字
						required: true,
						type: "text"
					},
					{
						title: "参与人数",
						placeholder: "请输入参与人数",
						inpValue: "",
						key: "peopleCount", //键名 接收对象名字
						required: true,
						type: "text"
					},
					{
						title: "参与内容",
						placeholder: "请输入参与内容",
						inpValue: "",
						key: "content", //键名 接收对象名字
						required: true,
						type: "textarea"
					},
				],
				list: []
			}
		},
		async mounted() {
			await this.getActivityListData(); // 获取活动列表
		},
		methods: {
			moveHandle() {},
			onSubAddActivisy() {
				this.title = "新建主题活动";
				this.$refs.popup.open();
			},
			close() {
				this.clearData();
				this.$refs.popup.close();
			},
			clearData(){
				this.inputData.forEach(item => {
				    item.inpValue = "";
				});
				this.beginTime = ""; // 活动开始时间
				this.endTime = ""; // 活动开始时间
				this.fileList = [];
				this.id = "";
			},
			startDateChange(even) {
				console.log(even)
				this.beginTime = even.value
			},
			endDateChange(even) {
				console.log(even)
				this.endTime = even.value
			},
			// 生成海报
			GeneratePoster(item){
				// 传递对象时将其转为 JSON 字符串
				let obj = { id: item.id, title: item.title, location: item.location, content: item.content, url: item.url, beginTime: item.beginTime, endTime: item.endTime, };
				
				uni.navigateTo({
				  url: '/pagesActivity/activity/poster?data=' + encodeURIComponent(JSON.stringify(obj))
				});
			},
			async delActivity(items){
				var that = this;
				// 将 uni.showModal 封装为 Promise
				const confirmSubmit = () => {
					return new Promise((resolve, reject) => {
						uni.showModal({
							title: '确认提交',
							content: '你确定要删除该活动吗？',
							success: function(res) {
								if (res.confirm) {
									resolve(); // 用户点击确认，继续执行提交操作
								} else if (res.cancel) {
									reject('用户取消提交'); // 用户点击取消，返回失败
								}
							}
						});
					});
				};
				
				try {
					// 等待用户确认
					await confirmSubmit();
				
					// 用户点击确认后执行的异步操作
					const result = await postSaveOrUpdateActivity({
						id:items.id,
						state:2, //删除
					});
				
					console.log("删除活动结果", result);
					if (result.code == 200) {
						// 提交成功后的操作
						that.$toast({
							title: "删除成功",
							icon: "success",
							success: () => {
								var nav = setTimeout(() => {
									that.getActivityListData();
									clearTimeout(nav)
								}, 500)
							}
						});
						
					} else {
						that.$toast({
							title: result.data.msg,
						});
					}
				
				} catch (err) {
					// 捕获用户取消或者提交失败的错误
					if (err === '用户取消提交') {
						console.log('用户取消提交');
					} else {
						that.$toast({
							icon: 'none',
							title: '发起失败，请联系管理员！',
							duration: 2000
						});
						console.log(err);
					}
				}
			},
			editActivity(items){
				// 遍历 inputData 数组，并根据 key 值匹配对象的属性值赋值给 inpValue
				this.inputData.forEach(item => {
				    if (items[item.key] !== undefined) {
				        item.inpValue = items[item.key];
				    }
				});
				this.beginTime = items.beginTime; // 活动开始时间
				this.endTime = items.endTime; // 活动开始时间
				this.fileList.push({
					url:items.url
				});
				this.title = "编辑主题活动";
				this.id = items.id;
				this.$refs.popup.open();
			},
			async getActivityListData() {
				try {
					const result = await getActivityList({});
					console.log("查询活动列表", result)
					if (result.code == 200) {
						this.list = result.data;
					} else {
						return this.$toast({
							title: result.data.msg,
						});
					}
				} catch (error) {
					console.error("请求失败", error);
					return this.$toast({
						title: "发起失败，请联系管理员！",
						icon: "error",
					});
				}
			},
			// 删除背景图
			async deleteBackground(e) {
				this.fileList = [];
				// const tempFilePath = e.tempFilePath;
				
				// try {
				// 	// 使用 await 等待文件上传完成
				// 	const deleFileResult = await postFileDelete({
				// 		fileName:tempFilePath
				// 	});
					
				// 	console.log(deleFileResult);
					
				// } catch (error) {
				// 	// 上传失败的处理
				// 	console.error('删除失败', error);
				// }
			},
			// 上传背景图后触发
			async selectBackground(e) {
				uni.showLoading({
					title: '正在上传图片...'
				});

				try {
					// 使用 await 等待文件上传完成
					const uploadResult = await postFileInsert(e.tempFilePaths[0]);

					// 上传成功的逻辑
					this.$toast({
						title: "上传成功",
						icon: "success"
					});

					uni.hideLoading();

					const response = JSON.parse(uploadResult.data); // 解析服务器返回的 JSON 数据
					
					this.fileList = [{
						url: response.msg
					}];
				} catch (error) {
					// 上传失败的处理
					uni.hideLoading();
					console.error('上传失败', error);
				}
			},
			// 提交
			async finsh() {
				let that = this;
				for (let i = 0; i < that.inputData.length; i++) {
					const item = that.inputData[i];
					if (item.required && item.inpValue === "") {
						that.$toast({
							title: item.placeholder,
							icon: "none"
						});
						return false; // 直接退出循环
					}
				}

				if (!that.beginTime) {
					return that.$toast({
						title: "请选择活动开始时间",
						icon: "none"
					});
				}
				if (!that.endTime) {
					return that.$toast({
						title: "请选择活动结束时间",
						icon: "none"
					});
				}
				if (that.fileList.length === 0) {
					return that.$toast({
						title: "请选择活动背景图",
						icon: "none"
					});
				}

				const resultObj = that.inputData.reduce((acc, item) => {
					// 使用 item.key 和 item.inpValue 更新 resultObj，并将 undefined 转为 ""
					acc[item.key] = item.inpValue !== undefined ? item.inpValue : "";
					return acc;
				}, {});
				
				// 做修改操作
				if(that.id && that.id != ""){
					resultObj.id = that.id;
				}
				
				resultObj.beginTime = that.beginTime;
				resultObj.endTime = that.endTime;
				// 使用正则表达式提取 `app/` 后面的部分
				let fileName = that.fileList[0].url.match(/app\/(.+)$/)[1];
				// let fileName = that.fileList[0].url.split('/').pop();
				resultObj.url = fileName;

				try {
					// 用户点击确认后执行的异步操作
					const result = await postSaveOrUpdateActivity(resultObj);

					console.log("新建活动结果", result);
					if (result.code == 200) {
						that.clearData();
						that.$refs.popup.close();
						that.$toast({
							title: "操作成功",
							icon: "success",
							success: () => {
								var nav = setTimeout(() => {
									that.getActivityListData();
									clearTimeout(nav)
								}, 500)
							}
						});

					} else {
						return that.$toast({
							title: result.data.msg,
						});
					}

				} catch (err) {
					that.$toast({
						icon: 'none',
						title: '发起失败，请联系管理员！',
						duration: 2000
					});
					console.log(err);
				}

			},
			//重置
			reset() {
				this.clearData();
			},
		}
	}
</script>

<style lang="scss" scoped>
	page {}

	.aclist {
		padding: 20rpx;
		background-color: #2698fb;

		.items {
			overflow: hidden;
			border: 1px solid #e8e8e8;
			background-color: #fff;
			border-radius: 20rpx;
			margin-bottom: 20rpx;
			padding: 15rpx;

			.items_i {
				width: 100%;
				height: 300rpx;
			}

			.items_z {
				padding: 10rpx;
				// color: #fff;
				font-size: 32rpx;
				font-weight: bold;
				display: flex;
				align-items: center;
			}

			.items_ar {
				display: flex;
				justify-content: space-between;
				align-items: center;
				color: #575959;
				font-size: 28rpx;
				padding: 10rpx;

				.ar_a {
					display: flex;
					align-items: center;
				}
			}

			.items_ti {
				display: flex;
				align-items: center;
				color: #999999;
				font-size: 28rpx;
				padding: 10rpx;
			}

			.items_c {
				color: #333333;
				font-size: 30rpx;
				padding: 10rpx 10rpx 5rpx 10rpx;
				letter-spacing: 2rpx;
				overflow: hidden;
				text-overflow: ellipsis;
				display: -webkit-box;
				-webkit-line-clamp: 2;
				line-height: 1.5;
				/*显示文本行数*/
				-webkit-box-orient: vertical;
			}

			.items_cz {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin: 20rpx 0 0;

				.items_czf {
					display: flex;
					align-items: center;

					.cz_btn {
						width: 100rpx;
						height: 45rpx;
						line-height: 45rpx;
						font-size: 20rpx;
						margin: 0;
						text-align: center;
						border-radius: 10rpx;
						margin-right: 10rpx;
					}

					.bianj {
						color: #00FF00;
						border: 1rpx solid #00FF00;
					}

					.shanc {
						color: #FF0000;
						border: 1rpx solid #FF0000;
					}
				}

				.haibao {
					width: 250rpx;
					height: 70rpx;
					line-height: 70rpx;
					background-image: linear-gradient(to right, #1984FD, #43A4F1);
					font-size: 30rpx;
					letter-spacing: 3px;
					color: #fff;
					margin: 0;
				}
			}

		}

		// 吸底工具栏
		.toolbars {
			position: fixed;
			left: 0;
			right: 0;
			bottom: var(--window-bottom);
			z-index: 1;
			height: 100rpx;
			display: flex;
			padding: 0 15rpx;
			align-items: center;
			border-top: 1rpx solid #ededed;
			border-bottom: 1rpx solid #ededed;
			background-color: #fff;
			box-sizing: border-box;

			.button-grounp {
				margin-left: auto;
				display: flex;
				justify-content: space-between;
				text-align: center;
				line-height: 72rpx;
				font-size: 13px;
				color: #fff;

				.button {
					width: 200rpx;
					margin: 0 10rpx;
					border-radius: 72rpx;
				}

				.payment-button {
					background-image: linear-gradient(to right, #1984FD, #43A4F1);

					&.disabled {
						opacity: 0.6;
					}
				}
			}
		}

		.filter-popup {
			color: #000000;

			.top-title {
				font-weight: bold;
				height: 90rpx;
				// margin-left: 70rpx;
				font-size: 34rpx;
				margin-top: 20rpx;

				.popup-title {
					// height: 100%;
					position: absolute;
					left: 50%;
					-webkit-transform: translateX(-50%);
					transform: translateX(-50%);
					white-space: nowrap;
				}

				.saasIcon {
					// width: 150rpx;
					// height: 100%;
					padding-right: 70rpx;
					font-size: 30rpx;
					margin-left: auto;
				}
			}

			.select-scroll {}

			.select-main,
			.input-main {
				padding: 0 32rpx;

				.input-item {
					display: flex;
					padding: 5rpx 0;
					// margin-top: 20rpx;
					border-bottom: 1px solid #f5f5f5;
					align-items: center;
					font-size: 30rpx;

					.input-label {
						color: #000000;
					}

					.input-field {
						flex: 1;
						padding-left: 15rpx;
						height: 70rpx;
						font-size: 30rpx;
						line-height: 70rpx;
					}
				}

				.input-items {
					display: flex;
					padding: 10rpx 0;
					// margin-top: 20rpx;
					border-bottom: 1px solid #f5f5f5;
					font-size: 30rpx;

					.input-label {
						color: #000000;
					}

					.input-textarea {
						flex: 1;
						padding-left: 15rpx;
						font-size: 30rpx;
					}
				}

			}

			.filter-button {
				width: 100%;
				height: 152rpx;
				background: #ffffff;
				box-shadow: 0px -3px 12px rgba(0, 0, 0, 0.06);
				position: fixed;
				bottom: 0;

				.btn {
					border-radius: 100rpx;
					margin-top: 26rpx;
					width: 680rpx;
					height: 80rpx;
					color: #ffffff;
					font-size: 28rpx;
					overflow: hidden;

					.btn-1 {
						flex: 1;
						background: linear-gradient(271deg, #2698fb 0%, #84c6ff 100%);
					}

					.btn-2 {
						flex: 1;
						background: linear-gradient(90deg, #0066ff 0%, #1371ff 100%);
					}
				}
			}

			// 自定义css
			.flex-row {
				display: flex;
			}

			.flex-row-c {
				display: flex;
				justify-content: center;
			}

			.flex-row--c {
				display: flex;
				align-items: center;
			}

			.flex-row-c-c {
				display: flex;
				justify-content: center;
				align-items: center;
			}

			.flex-row-sb {
				display: flex;
				// justify-content: space-between;
				justify-content: center;
				align-items: center;
				position: relative;
			}
		}

	}
</style>